/*子应用*/
const express = require("express")

const query = require("../pool")

const vertify = require("../modules/token")

const product = express.Router()

// 获取地址
product.get("/userAddress", async (req, res) => {
  let obj = req.query
  let uid = vertify.verifytoken(obj[0])
  if(!uid.uid){
    console.log("用户名不能为空")
  }else{
    let result = await query(`select * from cake_address where did=${uid.uid}`)
    if (result.length == 0) {
      res.send({ code: 0, msg: "未查询到相关结果" })
    } else {
      res.send({ code: 1, msg: "搜索成功", data: result })
    }
  }
})

// 默认地址切换
product.get("/isDef", async (req, res) => {
  let obj = req.query
  // console.log(obj)
  let uid = vertify.verifytoken(obj[0])
  // console.log(uid)
  // console.log(uid.uid)
  let isDef = await query(
    `update cake_address set isDefault=0 where did='${uid.uid}' and isDefault=1`
  )
  if (isDef.changedRows == 0) {
    res.send({ code: 0, msg: "失败" })
  } else {
    res.send({ code: 1, msg: "成功" })
  }
})

// 添加更新地址
product.get("/adduser", async (req, res) => {
  let obj = req.query
  // console.log(obj)
  // uid.uid = did
  let uid = vertify.verifytoken(obj.token)
  // console.log(uid)
  // console.log(obj)
  let rul2 = await query(`select * from cake_address where aid='${obj.aid}'`)
  // console.log(rul2)
  // 判断数据是否存在
  if (rul2.length != 0) {
    let rul2_1 = await query(
      `update cake_address set name='${obj.name}',province='${obj.province}',city='${obj.city}',county='${obj.county}',addressDetail='${obj.addressDetail}',address='${obj.address}',tel='${obj.tel}',isDefault=${obj.isDefault} where aid='${obj.aid}'`
    )
    if (rul2_1.changedRows == 0) {
      res.send({ code: 0, msg: "失败" })
    } else {
      res.send({ code: 1, msg: "成功" })
    }
  } else {
    let rul2_2 = await query(
      `insert into cake_address values(null,'${uid.uid}','${obj.name}','${obj.province}','${obj.city}','${obj.county}','${obj.addressDetail}','${obj.address}','${obj.tel}',${obj.isDefault});`
    )
    if (!rul2_2.changedRows) {
      res.send({ code: 0, msg: "失败" })
    } else {
      res.send({ code: 1, msg: "成功" })
    }
  }
})

// 删除地址
product.get("/del?:aid", async (req, res) => {
  let obj = req.query
  let result3 = await query(`delete from cake_address where aid=${obj.aid}`)
  if (result3.affectedRows == 0) {
    res.send({ code: 0, msg: "删除失败" })
  } else {
    res.send({ code: 1, msg: "删除成功" })
  }
})

//暴露
module.exports = product
